//index.js
//获取应用实例
let app = getApp()
var banner = require("./model/BannerModel.js");
var locationHelper = require('../../utils/location_helper.js');
var course = require('./model/CourseIndex.js')
var userModel=require('../my/model/UserModel.js')
var newsModel=require('../newslist/model/NewsModel.js')
var teacherModel = require('../teacher-home/model/TeacherModel.js')
var tripleDes = require('../../utils/CKCrypto.js')
Page({
  data: {
    localtionIcon: '../../images/icons/icon_selectgrade.png',
    _currentLevel: {},
    _changeLevelState:false,//年级是否更换
    _topNews:[],
    banners: [{
      id: 0,
      bannerUrl: '../../images/chalkasstes_background.png',
      targetUrl: ''
    }],
    option_models: [
      [{
        id: 0,
        name: '头条',
        icon: '../../images/icons/icon_toutiao.png',
        icon_background: '#FFFFFF',
        page_url: '../newslist/list'
        }, {
          id: 1,
          name: '作文库',
          icon: '../../images/icons/icon_zuowen.png',
          icon_background: '#FFFFFF',
          page_url: '../composition/index'
        }, {
          id: 2,
          name: '家长课堂',
          icon: '../../images/icons/icon_jiachang.png',
          icon_background: '#FFFFFF',
          page_url: '../parent-course/list'
        }, {
        id: 3,
        name: '分销专区',
        icon: '../../images/icons/icon_fenxiao.png',
        icon_background: '#FFFFFF',
          page_url: '../distribution/distribution'
      }]
    ],
    project_models: [
      [{
        id: 0,
        name: '语文',
        icon: '../../images/icons/icon_chinese.png',
        icon_background: '#FFFFFF',
        projectType:1,
        page_url: '../more-course/list'
      }, {
        id: 1,
        name: '数学',
        icon: '../../images/icons/icon_shuxue.png',
        icon_background: '#FFFFFF',
        projectType: 2,
        page_url: '../more-course/list'
      }, {
        id: 2,
        name: '英语',
        icon: '../../images/icons/icon_yingyu.png',
        icon_background: '#FFFFFF',
        projectType: 3,
        page_url: '../more-course/list'
      }, {
        id: 3,
        name: '更多',
        icon: '../../images/icons/icon_gengduo.png',
        icon_background: '#FFFFFF',
        projectType:-1,
        page_url: '../more-course/list'
      }]
    ],
    freeCourse:[],
    recomCourse:[],
    searchValue:''
  },
  //登入检测
  checkLogin: function() {
    var token = wx.getStorageSync("userToken")
    if (token == null || token.length <= 0) {
      wx.reLaunch({
        url: "../login/login",
      })
    }
  },
  //定位全新检测
  checkLocaltionPerssion:function(){
    console.log("start checkLocaltionPerssion...")
    var that=this
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化进入该页面,且未授权
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则无法获取您所需数据',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '授权失败',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用getLocationt的API
                      this.checkLocation(that)
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {//初始化进入
          this.checkLocation(that)
        }
        else { //授权后默认加载
          this.checkLocation(that)
        }
      }
    })
  },
  //获取定位
  checkLocation: function (that){
    console.log("start getLocation...")
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        locationHelper.getReverseGeocoder(res.latitude, res.longitude, function (addressRes) {
          console.log(addressRes)
          var mCity = addressRes.result.address_component.city
          var mAddress = addressRes.result.address;
          var mLat = addressRes.result.location.lat;
          var mLng = addressRes.result.location.lng;
          app.globalData.userLocationInfo = {
            lat: mLat,
            lng: mLng,
            address: mAddress,
            city: mCity
          }
        })
      },
    })
    that.loadData(that);
  },
  //加载数据
  loadData:function(that){
    course.getIndexFreeCourse(this.data._currentLevel.id, function (courses) {
      wx.stopPullDownRefresh()
      that.setData({
        freeCourse: courses,
        _changeLevelState:false
      })
    })
    course.getIndexRecomandCourse(this.data._currentLevel.id,function (courses) {
      wx.stopPullDownRefresh()
      that.setData({
        recomCourse: courses,
        _changeLevelState: false
      })
    })
  },
  onLoad: function() {
    var that = this
    this.checkLogin()
    userModel.getUserInfo(function (data) {
      getApp().globalData.userInfo = data
      that.setData({
        _currentLevel: { id: data.gradeLevel, text: data.gradeLevelText }
      })
    })
    this.checkLocaltionPerssion()
    
    banner.getBanners("0", function(data) {
      that.setData({
        banners: data
      })
    })
    banner.getSchoolBanners("-1", function (data) {
      that.setData({
        schoolbanners: data
      })
    })
    
  },
  onReady:function(){
    
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that=this
    newsModel.getToutiao("1", 1, function (data) {
      that.setData({
        _topNews: data
      })
    });
    if (this.data._changeLevelState){
      this.loadData(this)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.checkLocaltionPerssion()
    // setTimeout(function() {
    //   wx.stopPullDownRefresh()
    // }, 3000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  onShareAppMessage: function () {
    var shareObject = {
      title: "我发现一个有趣的学习平台，快来一起学习吧!",
      path: 'pages/index/index',
      success: function (res) {
        wx.showToast({
          title: '分享成功',
          icon: ''
        })
      }
    }
    return shareObject;
  },
  viewNewsMore:function(){
    wx.navigateTo({
      url: '../newslist/list',
    })
  },
  viewNewDtail:function(event){
    var _id = event.currentTarget.dataset.newid
    var _position = event.currentTarget.dataset.position
    var obj=this.data._topNews[_position];
    console.log(obj)
    wx.navigateTo({
      url: '../newsinfo/newsinfo?news=' + JSON.stringify(obj),
    })
  },
  //更多免费课程
  moreFreeCourse:function(){
    wx.navigateTo({
      url: '../more-course/list?reqType=1' + "&gradeLevel=" + this.data._currentLevel.id + "&showProjectFilter=1",
    })
  },
  //更多推荐课程
  moreRecomCourse: function () {
    wx.navigateTo({
      url: '../more-course/list?reqType=2' + "&gradeLevel=" + this.data._currentLevel.id + "&showProjectFilter=1",
    })
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  /**
   * banner切换监听
   */
  bannerChangeListener: function(event) {

  },
  onBannerItemClick: function(event) {
    var clickIndex = event.currentTarget.dataset.index
    var clickBanner = this.data.banners[clickIndex]
    wx.navigateTo({
      url: '../web/html?url=' + clickBanner.targetUrl,
    })
  },
  onSchoolBannerItemClick: function (event) {
    var clickIndex = event.currentTarget.dataset.index
    var clickBanner = this.data.schoolbanners[clickIndex]
    var _url = '../teacher-home/teacher?id=' + tripleDes.enCode(clickBanner.teacherId)
    console.log(_url);
    wx.navigateTo({
      url: _url,
    })
  },
  //功能操作吧item点击事件
  onOptionsItemClick: function (event) {
    var optObject = event.currentTarget.dataset.obj
    var _name = optObject.name
    var _url = optObject.page_url
    if (_url.length <= 0) {
      wx.showToast({
        title: '功能暂未开放，敬请期待！',
        icon: 'none'
      })
      return
    }
    if (optObject.name =='家长课堂'){
        wx.navigateTo({
          url: _url + '?gradeLevel=' + this.data._currentLevel.id + "&title=" + _name,
        })
    } else if (optObject.name == '学生课堂'){
      wx.navigateTo({
        url: _url + '?reqType=2' + "&gradeLevel=" + this.data._currentLevel.id + "&showProjectFilter=1" + "&title=" + _name
      })
    }else{
      wx.navigateTo({
        url: _url 
      })
    }
  },
  //课堂类目item点击事件
  onProjectItemClick: function(event) {
    var optObject = event.currentTarget.dataset.obj
    var _name = optObject.name
    var _url = optObject.page_url
    if (_url.length <= 0) {
      wx.showToast({
        title: '功能暂未开放，敬请期待！',
        icon: 'none'
      })
      return
    }
    var showProjectFilter=1
    if (optObject.projectType!=-1){
      showProjectFilter=0
    }
    wx.navigateTo({
      url: _url + "?projectType=" + optObject.projectType + "&gradeLevel=" + this.data._currentLevel.id + "&showProjectFilter=" + showProjectFilter + "&title=" + _name,
    })
  },
  /**
   * 选中位置
   */
  choseLocation: function(event) {
    wx.navigateTo({
      url: '../grade/list?gradeId=' + this.data._currentLevel.id + '&gradeText=' + this.data._currentLevel.text,
    })
  },
  /**
   * 搜索框输入监听
   */
  searchInput: function(event) {
    var input=event.detail.value
    this.setData({
      searchValue: input
    })
  },
  goSearchCourse:function(event){
    var value = this.data.searchValue
    if (value.length>0){
      wx.navigateTo({
        url: '../search/search?value=' + value,
      })
    }
  },
  /**
   * 输入完成
   */
  bindconfirm: function(event) {
    var inputValue = event.detail.value
    wx.showToast({
      title: '搜索：' + inputValue,
      icon: 'none'
    })
  },
  /**
   * 免费课程Item点击
   */
  onFreeItemClick: function(event) {
    var position = event.detail.position
    var id = event.detail.courseNo
    var title = event.detail.title
    var userName = ''
    if (Number(event.detail.showFullName) == 0) {//显示用户名
      userName = event.detail.teacherName
    } else {//显示全名称
      userName = event.detail.teacheRrealName
    }
    var _url = '../courseinfo/detail?courseId=' + id + '&title=' + title + '&teacherName=' + userName
    wx.navigateTo({
      url: _url,
    })
  },
  /**
   * 推荐课程Item点击
   */
  onRecommandItemClick: function (event) {
    var position = event.detail.position
    var id = event.detail.courseNo
    var title = event.detail.title
    var userName=''
    if (Number(event.detail.showFullName) == 0) {//显示用户名
      userName = event.detail.teacherName
    } else {//显示全名称
      userName = event.detail.teacheRrealName
    }
    var _url = '../courseinfo/detail?courseId=' + id + '&title=' + title + '&teacherName=' + userName
    wx.navigateTo({
      url: _url,
    })
  }
})